<template>
  <Board ref="board" :style="boardStyle" />
  <div v-show="state != 1" class="loading">
    <div v-show="state == 0" class="loading-icon"></div>
    <div v-show="state == 0">LOADING...</div>
    <div v-show="state == 2" class="error-icon"></div>
    <div v-show="state == 2">Failed to connect to the server, please reload the page to retry</div>
  </div>
</template>

<script>
import Board from './components/Board'
import { connect } from './api/connection'

export default {
  components: {
    Board
  },
  data() {
    return {
      boardMinWidth: 2000,
      boardMinHeight: 1400,
      boardWidth: 0,
      boardHeight: 0,
      scale: 1,
      state: 0, // 0: connecting, 1: connected, 2: disconnected
    }
  },
  computed: {
    boardStyle() {
      return {
        width: this.boardWidth + 'px',
        height: this.boardHeight + 'px',
        transform: `translate(-50%, -50%) scale(${this.scale})`
      }
    }
  },
  methods: {
    resize() {
      const windowWidth = window.innerWidth
      const windowHeight = window.innerHeight
      const scaleX = windowWidth / this.boardMinWidth
      const scaleY = windowHeight / this.boardMinHeight
      this.scale = Math.min(scaleX, scaleY)
      this.boardWidth = windowWidth / this.scale
      this.boardHeight = windowHeight / this.scale
    }
  },
  mounted() {
    this.resize()
    window.onresize = this.resize
    connect(con => {
      this._con = con
      this.state = 1
    }, () => this.state = 2, this.$refs.board.handleMessage)
  }
}
</script>

<style>
@keyframes rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

html,
body {
  height: 100%;
}

body {
  margin: 0;
  overflow: hidden;
  user-select: none;
}

.board {
  left: 50%;
  top: 50%;
}

.loading {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 30px;
}

.loading-icon {
  margin-right: 20px;
  width: 70px;
  height: 70px;
  border: 4px solid;
  border-color: black transparent black transparent;
  border-radius: 50%;
  animation: 1s linear infinite rotate;
}

.error-icon {
  position: relative;
  margin-right: 20px;
  width: 70px;
  height: 70px;
  border: 5px solid red;
  border-radius: 50%;
}

.error-icon::before,
.error-icon::after {
  content: ' ';
  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  height: 10px;
  background-color: red;
}

.error-icon::before {
  transform: translateY(-50%) rotate(45deg);
}

.error-icon::after {
  transform: translateY(-50%) rotate(-45deg);
}
</style>
